package spider.com.fenwe.util;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.util.zip.GZIPInputStream;

import javax.servlet.http.HttpServletRequest;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 统一http请求工具类
 * @author miaoqiang
 * @date 20160203
 */
public class HttpUtil {
    public static Logger log = LoggerFactory.getLogger(HttpUtil.class);

    public static String post(String json, String url) {
        HttpPost httpPost = null;
        String jsonOut = "";
        HttpResponse response = null;
        try {
            StringEntity entity = new StringEntity(json, "utf-8");
            entity.setContentType("application/json");
            DefaultHttpClient client = new DefaultHttpClient();
            httpPost = new HttpPost(url);
            httpPost.setEntity(entity);
            response = client.execute(httpPost);

        } catch (IOException e) {
            log.error("HttpUtil post(" + json + "," + url + ")" + "请求发生异常", e);
        }
        if (response == null) {
            return "";
        }
        try (InputStream inputStream = response.getEntity().getContent();
                InputStreamReader inputReader = new InputStreamReader(inputStream);
                BufferedReader bufferReader = new BufferedReader(inputReader);) {
            StringBuffer buffer = new StringBuffer();
            String str = new String("");
            while ((str = bufferReader.readLine()) != null) {
                buffer.append(str);
            }
            jsonOut = buffer.toString();
        } catch (IllegalStateException | IOException e) {
            log.error("HttpUtil post(" + json + "," + url + ")" + "请求发生异常", e);
        }
        if (httpPost != null) {
            httpPost.releaseConnection();
        }
        return jsonOut;

    }

    public static String post(String json, URI url) {
        HttpPost httpPost = null;
        String jsonOut = "";
        HttpResponse response = null;
        try {
            StringEntity entity = new StringEntity(json, "utf-8");
            entity.setContentType("application/json");
            DefaultHttpClient client = new DefaultHttpClient();
            httpPost = new HttpPost(url);
            httpPost.setEntity(entity);
            response = client.execute(httpPost);
        } catch (IOException e) {
            log.error("HttpUtil post(" + json + "," + url + ")" + "请求发生异常", e);
        }
        if (response == null) {
            return "";
        }
        try (InputStream inputStream = response.getEntity().getContent();
                InputStreamReader inputReader = new InputStreamReader(inputStream);
                BufferedReader bufferReader = new BufferedReader(inputReader);) {
            StringBuffer buffer = new StringBuffer();
            String str = new String("");
            while ((str = bufferReader.readLine()) != null) {
                buffer.append(str);
            }
            jsonOut = buffer.toString();
        } catch (IllegalStateException | IOException e) {
            log.error("HttpUtil post(" + json + "," + url + ")" + "请求发生异常", e);
        }
        return jsonOut;
    }

    public static String get(String url) {
        HttpGet httpGet = null;
        String jsonOut = "";
        HttpResponse response = null;

        DefaultHttpClient client = new DefaultHttpClient();
        httpGet = new HttpGet(url);
        try {
            response = client.execute(httpGet);
        } catch (IOException e) {
            log.error("HttpUtil get(" + url + ")" + "请求发生异常", e);
        }
        if (response == null) {
            return "";
        }
        try (InputStream inputStream = response.getEntity().getContent();
                InputStreamReader inputReader = new InputStreamReader(inputStream, "UTF-8");
                BufferedReader bufferReader = new BufferedReader(inputReader);) {
            StringBuffer buffer = new StringBuffer();
            String str = new String("");
            while ((str = bufferReader.readLine()) != null) {
                buffer.append(str);
            }
            jsonOut = buffer.toString();
        } catch (IllegalStateException | IOException e) {
            log.error("HttpUtil get(" + url + ")" + "请求发生异常", e);
        }
        httpGet.releaseConnection();
        return jsonOut;
    }

    public static String get(String url, String headerKey, String headerVal) {
        HttpGet httpGet = null;
        String jsonOut = "";
        HttpResponse response = null;
        DefaultHttpClient client = new DefaultHttpClient();
        httpGet = new HttpGet(url);
        if (httpGet != null) {
            httpGet.addHeader(headerKey, headerVal);
        }
        try {
            response = client.execute(httpGet);
        } catch (IOException e) {
            log.error("HttpUtil get(" + url + "," + headerKey + "," + headerVal + ")" + "请求发生异常", e);
        }
        if (response == null) {
            return "";
        }
        try (InputStream inputStream = response.getEntity().getContent();
                InputStreamReader inputReader = new InputStreamReader(inputStream, "UTF-8");
                BufferedReader bufferReader = new BufferedReader(inputReader);) {
            StringBuffer buffer = new StringBuffer();
            String str = new String("");

            while ((str = bufferReader.readLine()) != null) {
                buffer.append(str);
            }
            jsonOut = buffer.toString();
        } catch (IllegalStateException | IOException e) {
            log.error("HttpUtil get(" + url + "," + headerKey + "," + headerVal + ")" + "请求发生异常", e);
        }
        if (httpGet != null) {
            httpGet.releaseConnection();
        }
        return HttpUtil.convertUnicode(jsonOut);
    }

    public static String get(String json, String url) {
        DefaultHttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url + json);
        StringBuffer buffer = new StringBuffer();
        HttpResponse response = null;
        String jsonOut = "";
        try {
            response = client.execute(httpGet);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        if (response == null) {
            return "";
        }
        try (InputStream inputStream = response.getEntity().getContent();
                InputStreamReader inputReader = new InputStreamReader(inputStream, "UTF-8");
                BufferedReader bufferReader = new BufferedReader(inputReader)) {
            String str = new String("");
            while ((str = bufferReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferReader.close();
            jsonOut = buffer.toString();
        } catch (Exception e) {
            log.error("HttpUtil get(" + url + "," + json + ")" + "请求发生异常", e);
        }
        httpGet.releaseConnection();
        return jsonOut;
    }

    public static String xmlGet(String json, String url) {
        HttpGet httpGet = null;
        String jsonOut = "";
        HttpResponse response = null;
        try {
            DefaultHttpClient client = new DefaultHttpClient();
            httpGet = new HttpGet(url);
            httpGet.setHeader("Accept-Encoding", "gzip, deflate");
            response = client.execute(httpGet);
        } catch (IOException e) {
            log.error("HttpUtil xmlGet(" + json + "," + url + ")" + "请求发生异常", e);
        }
        if (response == null) {
            return "";
        }
        try (InputStream inputStream = response.getEntity().getContent();
                GZIPInputStream gzin = new GZIPInputStream(inputStream);
                InputStreamReader inputReader = new InputStreamReader(gzin, "UTF-8");
                BufferedReader bufferReader = new BufferedReader(inputReader);) {
            StringBuffer buffer = new StringBuffer();
            String str = new String("");
            while ((str = bufferReader.readLine()) != null) {
                buffer.append(str);
            }
            jsonOut = buffer.toString();
        } catch (IllegalStateException | IOException e) {
            log.error("HttpUtil xmlGet(" + json + "," + url + ")" + "请求发生异常", e);
        }
        httpGet.releaseConnection();
        return jsonOut;
    }

    public static String put(String url, String json) {
        HttpPut httpPut = null;
        String jsonOut = "";
        HttpResponse response = null;
        try {
            StringEntity entity = new StringEntity(json, "utf-8");
            entity.setContentType("application/json");
            DefaultHttpClient client = new DefaultHttpClient();
            httpPut = new HttpPut(url);
            httpPut.setEntity(entity);
            response = client.execute(httpPut);
        } catch (IOException e) {
            log.error("HttpUtil put(" + url + "," + json + ")" + "请求发生异常", e);
        }
        if (response == null) {
            return "";
        }
        try (InputStream inputStream = response.getEntity().getContent();
                InputStreamReader inputReader = new InputStreamReader(inputStream);
                BufferedReader bufferReader = new BufferedReader(inputReader);) {
            StringBuffer buffer = new StringBuffer();
            String str = new String("");
            while ((str = bufferReader.readLine()) != null) {
                buffer.append(str);
            }
            jsonOut = buffer.toString();
        } catch (IllegalStateException | IOException e) {
            log.error("HttpUtil put(" + url + "," + json + ")" + "请求发生异常", e);
        }
        if (httpPut != null) {
            httpPut.releaseConnection();
        }

        return jsonOut;
    }

    public static String put(URI url, String json) throws Exception {
        HttpPut httpPut = null;
        HttpResponse response = null;
        String jsonOut = "";
        try {
            StringEntity entity = new StringEntity(json, "utf-8");
            entity.setContentType("application/json");
            DefaultHttpClient client = new DefaultHttpClient();
            httpPut = new HttpPut(url);
            httpPut.setEntity(entity);
            response = client.execute(httpPut);
        } catch (IOException e) {
            log.error("HttpUtil put(" + url + "," + json + ")" + "请求发生异常", e);
        }
        if (response == null) {
            return "";
        }
        try (InputStream inputStream = response.getEntity().getContent();
                InputStreamReader inputReader = new InputStreamReader(inputStream);
                BufferedReader bufferReader = new BufferedReader(inputReader);) {
            StringBuffer buffer = new StringBuffer();
            String str = new String("");
            while ((str = bufferReader.readLine()) != null) {
                buffer.append(str);
            }
            jsonOut = buffer.toString();

        } catch (IllegalStateException | IOException e) {
            log.error("HttpUtil put(" + url + "," + json + ")" + "请求发生异常", e);
        }
        if (httpPut != null) {
            httpPut.releaseConnection();
        }

        return jsonOut;
    }

    public static String delete(String url) throws Exception {
        HttpDelete httpDelete = null;
        String jsonOut = "";
        HttpResponse response = null;
        DefaultHttpClient client = new DefaultHttpClient();
        httpDelete = new HttpDelete(url);
        try {
            response = client.execute(httpDelete);
        } catch (IOException e) {
            log.error("HttpUtil delete(" + url + ")" + "请求发生异常", e);
        }
        if (response == null) {
            return "";
        }
        try (InputStream inputStream = response.getEntity().getContent();
                InputStreamReader inputReader = new InputStreamReader(inputStream, "UTF-8");
                BufferedReader bufferReader = new BufferedReader(inputReader);) {
            StringBuffer buffer = new StringBuffer();
            String str = new String("");
            while ((str = bufferReader.readLine()) != null) {
                buffer.append(str);
            }
            jsonOut = buffer.toString();
        } catch (IllegalStateException | IOException e) {
            log.error("HttpUtil delete(" + url + ")" + "请求发生异常", e);
        }
        httpDelete.releaseConnection();
        return jsonOut;
    }

    public static String delete(URI url) throws Exception {
        HttpDelete httpDelete = null;
        String jsonOut = "";
        HttpResponse response = null;
        DefaultHttpClient client = new DefaultHttpClient();
        httpDelete = new HttpDelete(url);
        try {
            response = client.execute(httpDelete);
        } catch (IOException e) {
            log.error("HttpUtil delete(" + url + ")" + "请求发生异常", e);
        }
        if (response == null) {
            return "";
        }
        try (InputStream inputStream = response.getEntity().getContent();
                InputStreamReader inputReader = new InputStreamReader(inputStream, "UTF-8");
                BufferedReader bufferReader = new BufferedReader(inputReader);) {
            StringBuffer buffer = new StringBuffer();
            String str = new String("");
            while ((str = bufferReader.readLine()) != null) {
                buffer.append(str);
            }
            jsonOut = buffer.toString();
        } catch (IllegalStateException | IOException e) {
            log.error("HttpUtil delete(" + url + ")" + "请求发生异常", e);
        }
        httpDelete.releaseConnection();
        return jsonOut;
    }

    public static String getRequestIP(HttpServletRequest httpRequest) {
        String ip = "";
        if (httpRequest.getHeader("X_forward_for") != null) {
            ip = httpRequest.getHeader("X_forward_for");
        } else {
            ip = httpRequest.getRemoteAddr();
        }
        return ip;
    }

    /**
     * 编码转换
     * 
     * @param ori
     * @return
     */
    public static String convertUnicode(String ori) {
        char aChar;
        int len = ori.length();
        StringBuffer outBuffer = new StringBuffer(len);
        for (int x = 0; x < len;) {
            aChar = ori.charAt(x++);
            if (aChar == '\\') {
                aChar = ori.charAt(x++);
                if (aChar == 'u') {
                    // Read the xxxx
                    int value = 0;
                    for (int i = 0; i < 4; i++) {
                        aChar = ori.charAt(x++);
                        switch (aChar) {
                        case '0':
                        case '1':
                        case '2':
                        case '3':
                        case '4':
                        case '5':
                        case '6':
                        case '7':
                        case '8':
                        case '9':
                            value = (value << 4) + aChar - '0';
                            break;
                        case 'a':
                        case 'b':
                        case 'c':
                        case 'd':
                        case 'e':
                        case 'f':
                            value = (value << 4) + 10 + aChar - 'a';
                            break;
                        case 'A':
                        case 'B':
                        case 'C':
                        case 'D':
                        case 'E':
                        case 'F':
                            value = (value << 4) + 10 + aChar - 'A';
                            break;
                        default:
                            throw new IllegalArgumentException("Malformed   \\uxxxx   encoding.");
                        }
                    }
                    outBuffer.append((char) value);
                } else {
                    if (aChar == 't')
                        aChar = '\t';
                    else if (aChar == 'r')
                        aChar = '\r';
                    else if (aChar == 'n')
                        aChar = '\n';
                    else if (aChar == 'f')
                        aChar = '\f';
                    outBuffer.append(aChar);
                }
            } else
                outBuffer.append(aChar);

        }
        return outBuffer.toString();
    }

    /**
     * 根据地址获得数据的字节流
     * @param strUrl 网络连接地址
     * @return
     */
    public static byte[] getImageFromNetByUrl(String strUrl) {
        try {
            System.out.println("in get method-----" + strUrl);
            URL url = new URL(strUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5 * 1000);
            InputStream inStream = conn.getInputStream();// 通过输入流获取图片数据
            byte[] btImg = readInputStream(inStream);// 得到图片的二进制数据
            return btImg;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 从输入流中获取数据
     * @param inStream 输入流
     * @return
     * @throws Exception
     */
    public static byte[] readInputStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        inStream.close();
        return outStream.toByteArray();
    }

    /**
     * 将图片写入到磁盘
     * @param img 图片数据流
     * @param fileName 文件保存时的名称
     */
    public static void writeImageToDisk(String url, String fileName) {
        try {
            byte[] img = getImageFromNetByUrl(url);
            if (img.length > 20480) {
                File file = new File(fileName);
                FileOutputStream fops = new FileOutputStream(file);
                fops.write(img);
                fops.flush();
                fops.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void writeImageToDisk2(String url, String fileName) {
        url = url.replaceAll("&", "llll");
        Runtime rt = Runtime.getRuntime();
        // phantomjs 和codes.js的路径之间有个空格 本代码只是测试用的绝对路径
        // Process p = rt.exec("cmd.exe /c ipconfig/all");
        String[] comands = { "cmd.exe", "/c", "phantomjs",
                "D:\\workspace\\20161114\\spider\\src\\spider\\com\\fenwe\\sourcesFolder\\getPage3.js", url };
        // String[] comands = { "cmd.exe", "/c", "start",
        // "F:\\phantomjs\\phantomjs-2.1.1-windows\\phantomjs-2.1.1-windows\\bin\\phantomjs.exe"
        // };
        ProcessBuilder builder = new ProcessBuilder();
        builder.command(comands);
        try {
            Process p = builder.start();
            InputStream is = p.getInputStream();
            byte[] img = readInputStream(is);
            System.out.println("size-----" + img.length);
            if (img.length > 20480) {
                File file = new File(fileName);
                FileOutputStream fops = new FileOutputStream(file);
                fops.write(img);
                System.out.println("save -------" + fileName);
                fops.flush();
                fops.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String getAjaxCotnent(String url) throws IOException {
        url = url.replaceAll("&", "llll");
        Runtime rt = Runtime.getRuntime();
        // phantomjs 和codes.js的路径之间有个空格 本代码只是测试用的绝对路径
        // Process p = rt.exec("cmd.exe /c ipconfig/all");
        String[] comands = { "cmd.exe", "/c", "phantomjs",
                "D:\\workspace\\20161114\\spider\\src\\spider\\com\\fenwe\\sourcesFolder\\getPage3.js", url };
        // String[] comands = { "cmd.exe", "/c", "start",
        // "F:\\phantomjs\\phantomjs-2.1.1-windows\\phantomjs-2.1.1-windows\\bin\\phantomjs.exe"
        // };
        ProcessBuilder builder = new ProcessBuilder();
        builder.command(comands);
        Process p = builder.start();
        InputStream is = p.getInputStream();
        // new RunThread(p.getInputStream(), "INFO").start();
        // new RunThread(p.getErrorStream(), "ERR").start();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        // FileOutputStream fileOutputStream = new FileOutputStream(
        // "D:\\workspace\\20161114\\spider\\src\\spider\\com\\fenwe\\sourcesFolder\\a.txt",
        // false);
        // byte[] b = new byte[1024];
        // while ((is.read(b)) != -1) {
        // fileOutputStream.write(b);
        // }
        StringBuffer sbf = new StringBuffer();
        String tmp = "";
        while ((tmp = br.readLine()) != null) {
            sbf.append(tmp);
        }
        try {
            int res = p.waitFor();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // return sbf.toString();
        return sbf.toString();
    }
}
